/*
 * @Author: xiaosihan 
 * @Date: 2021-12-21 17:29:58 
 * @Last Modified by: xiaosihan
 * @Last Modified time: 2022-02-11 15:46:19
 */

import Transition from "three-base/Transition";
import { Group, PointsMaterial, Texture, Vector3 } from "three";
import BlueLine from "./BlueLine";
import Btn from "./Btn";
import LightPoint from "./lightPoint";
import RingMesh from "./RingMesh";


export default class BtnItem extends Group {
    constructor(btnText: string) {
        super();
        this.init(btnText);

        this.transition.setBezier([0.5, 0.5, 0.5, 0.5]);
        this.transition.setDuration(500);
    }

    delay = 0;

    openTime?: NodeJS.Timeout;

    // 展开特效
    open() {
        this.openTime = setTimeout(() => {
            this.transition.set({
                x: this.endPosition.x,
                y: this.endPosition.y,
                z: this.endPosition.z
            });
        }, this.delay);
    }

    // 收起特效
    close() {
        if (this.openTime) {
            clearTimeout(this.openTime);
        }

        this.transition.set({
            x: this.startPosition.x,
            y: this.startPosition.y,
            z: this.startPosition.z
        });
    }

    startPosition = new Vector3(0, 190, 0);

    endPosition = new Vector3(0, 0, 0);

    transition = (() => {
        const transition = new Transition({ x: 0, y: 190, z: 0 });

        transition.onChange(async ({ x, y, z }) => {

            await new Promise(resolve => requestAnimationFrame(resolve));

            this.position.set(x, y, z);

            this.lightPoint.visible = (y !== 190);
            this.ringMesh.visible = (y === 20);
            this.btn.visible = (y === 20);

            const instanceStart = this.blueLine.geometry.getAttribute("instanceStart");
            instanceStart.setXYZ(0, -x, 190 - y, -z);
            instanceStart.setXYZ(1, 0, y, 0);
            instanceStart.needsUpdate = true;
        });

        return transition;
    })();

    // 按钮
    btn!: Btn;

    // 光点
    lightPoint = new LightPoint();

    // 圆环
    ringMesh = new RingMesh();

    // 蓝色的线
    blueLine = new BlueLine();

    set customScale(v: number) {
        this.btn.customScale = v;
    }

    get customScale() {
        return this.btn.customScale;
    }

    init(btnText: string) {
        // 添加按钮
        this.btn = new Btn(btnText);
        this.btn.name = btnText;
        this.btn.position.set(0, 20, 0);
        this.btn.userData = { cursor: "pointer" };
        this.btn.addEventListener("click", (e) => {
            this.dispatchEvent({ type: "click", e } as never);
        });

        this.add(this.btn);

        // 添加光点
        ((this.lightPoint.material as PointsMaterial).map as Texture).offset.set(0, 0);
        this.lightPoint.position.set(0, 0, 0)
        this.add(this.lightPoint);

        this.add(this.ringMesh);

        this.add(this.blueLine);
    }

    // 点击事件
    onClick?: () => void;


}